package com.bawei.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.bawei.common.constant.SeckillConstant;
import com.bawei.common.utils.R;
import com.bawei.seckill.feign.GoodsFeignService;
import com.bawei.seckill.service.SeckillService;
import com.bawei.seckill.vo.SeckillListEntityVo;
import com.bawei.seckill.vo.SeckillToRedis;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private GoodsFeignService goodsFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void uploadSeckillSkuLatestDays() {
        //远程查询商品获取需要秒杀的商品
     R goodsVo  = goodsFeignService.getLates3DaySession();
     //判断要有没有商品
     if (!goodsVo.get("code").equals("500")){
         //Object list = goodsVo.get("list");
         //String s = JSON.toJSONString(list);

         List<SeckillListEntityVo> listEntityVos = goodsVo.getData(new TypeReference<List<SeckillListEntityVo>>(){});

         listEntityVos.stream().forEach(seckillListEntityVo -> {
             //准备绑定哈希
             BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SeckillConstant.SESSION__CACHE_PREFIX);

             //绑定当前时间段的所有商品id
             Long start = seckillListEntityVo.getSeckillStarttime().getTime();
             Long end = seckillListEntityVo.getSeckillEndtime().getTime();
             //判断redis中有没有
             String key= SeckillConstant.SESSION__CACHE_PREFIX+start+"_"+end;

             if (!ops.hasKey(key)){
                 //生成随机码
                 String token = UUID.randomUUID().toString().replace("-", "");
                 SeckillToRedis redis = new SeckillToRedis();

                 BeanUtils.copyProperties(seckillListEntityVo,redis );

                 redis.setRandomCode(token);
                 String s1 = JSON.toJSONString(redis);
                 ops.put(key,s1);

                 //如果当前这个场次的商品库存信息已经上架就不需要上架
                 //5、使用库存作为分布式Redisson信号量（限流）
                 // 使用库存作为分布式信号量
                 RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + token);
                 // 商品可以秒杀的数量作为信号量
                 semaphore.trySetPermits(redis.getSeckillNum());

             }

         });
     }
    }
}
